<template>
  <div class="ele-body">
    <a-card :bordered="false" title="首饰盘点(门店)信息">
      <a-form
        class="margin-y-15"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{
          md: { span: 17 },
          sm: { span: 20 },
          xs: { span: 24 }
        }"
      >
        <a-row :gutter="24">
          <a-col :md="8" :sm="24" :xs="24">
            <div style="height: calc(100vh - 350px)">
              <vxe-table align="center" :data="tableData">
                <vxe-column field="location" title="盘点位置" />
                <vxe-column field="count" title="应盘" />
                <vxe-column field="num" title="实盘" />
              </vxe-table>
            </div>

            <a-space class="margin-y-30">
              <a-button
                type="primary"
                class="ele-btn-icon"
                v-if="receipts.status == 0"
                @click="over()"
                ><span>结束盘点</span></a-button
              >
              <a-button
                type="default"
                class="ele-btn-icon"
                v-if="
                  receipts.status == 0 ||
                  (receipts.status && receipts.status != 1)
                "
                @click="restart()"
                ><span>重新盘点</span></a-button
              >
            </a-space>
          </a-col>
          <a-col :md="16" :sm="24" :xs="24">
            <table cellpadding="0" cellspacing="0" class="recepit_table2">
              <tbody>
                <tr>
                  <td class="tit">货品大类</td>
                  <td>{{ receipts.class_name }}</td>
                  <td class="tit">货品种类</td>
                  <td>{{ receipts.subclass_name }}</td>
                  <td class="tit">货品款式</td>
                  <td>{{ receipts.style_name }}</td>
                </tr>
                <tr>
                  <td class="tit">供应商款式</td>
                  <td>{{ receipts.supplier_name }}</td>
                  <td class="tit">系列名称</td>
                  <td>{{ receipts.series_name }}</td>
                  <td class="tit">宝石类别</td>
                  <td>{{ receipts.gem_category_name }}</td>
                </tr>
              </tbody>
            </table>
            <div class="margin-top-15">
              <a-space class="margin-y-30">
                <a-button
                  type="primary"
                  class="ele-btn-icon"
                  v-if="receipts.status == 0"
                  @click="luru()"
                  ><span>批量录入</span></a-button
                >
              </a-space>
              <vxe-grid v-bind="gridOptions">
                <template #count_edit="{ row, column }">
                  <vxe-input
                    v-model="row.real_num"
                    @change="numChangeEvent(row, column)"
                  />
                </template>
              </vxe-grid>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 批量录入条码弹窗 -->
    <ele-modal
      :width="750"
      :visible="visible"
      :confirm-loading="loading"
      title="批量录入条码"
      :body-style="{ paddingBottom: '8px' }"
      @update:visible="updateVisible"
      @ok="save"
    >
      <a-form
        :wrapper-col="{ md: { span: 24 }, sm: { span: 24 }, xs: { span: 24 } }"
      >
        <a-row :gutter="24">
          <a-col :md="12" :sm="12" :xs="12">
            <a-form-item>
              <div class="hd_left">
                <div class="hd_title">批量录入条码（每行一个）：</div>
                <div class="hd_inp"
                  ><a-textarea
                    class="hd_inp_con"
                    placeholder="请输入"
                    v-model:value="val"
                    allow-clear
                    @change="change"
                /></div>
              </div>
              <div class="fs-14 flex justify-end"
                ><a @click="delrec()">删除重复条码</a></div
              >
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="12" :xs="12">
            <a-form-item>
              <div>
                <div class="fs-14 color-999">1、每行一个条码</div>
                <div class="fs-14 margin-top-30"
                  ><a @click="clear()">清空条码</a></div
                >
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
  import { ref, reactive, unref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { message, Modal } from 'ant-design-vue';
  import {
    continue_check,
    check_detail,
    check_edit_num,
    batch_enter,
    check_reset,
    check_finish
  } from '@/api/jewelry/receipts_store_check';

  const { currentRoute, push } = useRouter();
  const { query } = unref(currentRoute);

  const loading = ref(false);
  const visible = ref(false);
  const receipts = ref({});
  const tableData = ref([]);
  const val = ref(null);
  const bar_code = ref([]);
  const bar_code2 = ref([]);

  onMounted(async () => {
    /* if (query.form == 'add') {
		await continue_check({ code: query.code }).then(res => {});
	} */
    await getDetail();
  });
  const getDetail = () => {
    check_detail({ code: query.code }).then((res) => {
      receipts.value = res.data.receipts;
      gridOptions.data = res.data.receipts_goods;
      tableData.value = [];
      tableData.value.push({
        location: res.data.location,
        count: res.data.count,
        num: res.data.num
      });
      console.log('tableData', tableData.value);
    });
  };
  const numChangeEvent = (row, column) => {
    edit(row.code, row.real_num);
  };
  const edit = (goodsCode, num) => {
    check_edit_num({ code: query.code, goods_code: goodsCode, num: num })
      .then((res) => {
        getDetail();
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e);
      });
  };
  const luru = () => {
    visible.value = true;
  };

  const change = (e) => {
    console.log(e.target.value);
    bar_code.value = e.target.value.split(/[(\r\n)\r\n]+/);
    bar_code2.value = [];
    bar_code.value.forEach((item, index) => {
      let arr = item.split(',');
      bar_code2.value[index] = {
        bar_code: arr[0],
        num: 1
      };
      if (arr[1]) {
        bar_code2.value[index].num = arr[1];
      }
    });
    console.log('bar_code2', bar_code2.value);
  };
  //清空条码
  const clear = () => {
    Modal.confirm({
      title: '提示',
      content: '确定清空条码?',
      maskClosable: true,
      onOk: () => {
        val.value = null;
        bar_code.value = [];
        bar_code2.value = [];
      },
      onCancel: () => {}
    });
  };
  //删除重复条码
  const delrec = () => {
    //console.log('val', val.value);
    bar_code.value = val.value.split(/[(\r\n)\r\n]+/);
    bar_code.value = norepeat(bar_code.value);
    val.value = bar_code.value.join('\n');
    bar_code2.value = [];
    bar_code.value.forEach((item, index) => {
      let arr = item.split(',');
      bar_code2.value[index] = {
        bar_code: arr[0],
        num: 1
      };
      if (arr[1]) {
        bar_code2.value[index].num = arr[1];
      }
    });
    //norepeat(bar_code2.value);
  };

  const save = () => {
    console.log('bar_code2', bar_code2.value);
    batch_enter({ code: query.code, goods: bar_code2.value })
      .then((res) => {
        getDetail();
        message.success(res.msg);
        updateVisible();
      })
      .catch((e) => {
        message.error(e);
      });
  };
  const over = () => {
    check_finish({ code: query.code })
      .then((res) => {
        getDetail();
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e);
      });
  };
  const restart = () => {
    check_reset({ code: query.code })
      .then((res) => {
        getDetail();
        message.success(res.msg);
      })
      .catch((e) => {
        message.error(e);
      });
  };
  const updateVisible = () => {
    visible.value = !visible.value;
  };

  const gridOptions = reactive({
    border: true,
    height: 500,
    rowConfig: {
      keyField: 'id'
    },
    columnConfig: {
      resizable: true
    },
    pagerConfig: {
      pageSize: 10
    },
    editConfig: {
      trigger: 'click',
      mode: 'cell',
      beforeEditMethod({ row, columnIndex }) {
        console.log('kk', receipts.value.status);
        if (receipts.value.status == 1 && columnIndex === 16) {
          return false;
        }
        return true;
      }
    },
    columns: [
      { field: 'bar_code', title: '条码', fixed: 'left', width: '100' },
      { field: 'name', title: '货品名称', width: '150' },
      { field: 'subclass_name', title: '货品种类', width: '150' },
      { field: 'class_name', title: '货品大类', width: '150' },
      { field: 'quality_name', title: '货品成色', width: '150' },
      { field: 'style_name', title: '货品款式', width: '150' },
      { field: 'sub_style', title: '二级款式', width: '150' },
      { field: 'gold_weight', title: '净金重(g)', width: '150' },
      { field: 'piece_weight', title: '总件重(g)', width: '150' },
      { field: 'style_model', title: '款号', width: '150' },
      { field: 'sticker_price', title: '标签价', width: '150' },
      { field: 'cost', title: '成本价', width: '150' },
      { field: 'retail_labour_expenses', title: '零售价/工费', width: '150' },
      { field: 'role0', title: '零售倍率', width: '150' },
      { field: 'num', title: '应盘数量', width: '150' },
      { field: 'check_num', title: '盘盈', width: '150' },
      {
        field: 'real_num',
        title: '实盘数量',
        width: '150',
        fixed: 'right',
        editRender: {},
        slots: { edit: 'count_edit' }
      }
    ],
    data: []
  });

  const norepeat = (arr) => {
    console.log('arr000', arr);
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {
      if (newArr.indexOf(arr[i]) == -1) {
        //解释：如果新数组里没有就放进去，有就放不进了
        newArr.push(arr[i]);
      }
    }
    console.log('newArr', newArr);
    return newArr;
  };
</script>

<style lang="less" scoped>
  .hd_left {
    height: calc(100vh - 320px);
  }
  .hd_inp {
    height: calc(100vh - 400px);
  }
</style>
